package zouran.shounewsspringboot.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import zouran.shounewsspringboot.entity.ResultMap;

import java.util.Arrays;

/**
 * Author：zouran
 * Date：2023/3/30  17:31
 * Description:Handler All Exception
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final ResultMap<Object> resultMap;
    public GlobalExceptionHandler(ResultMap<Object> resultMap) {
        this.resultMap = resultMap;
    }
    /**
     *description:NullPointerException
     */
    @ExceptionHandler(value=NullPointerException.class)
    public ResultMap<Object> NullExceptionHandler(NullPointerException e){
    log.info("NullPointerException");
        System.out.println(Arrays.toString(e.getStackTrace()).split(",")[0]);
         return resultMap.error();
    }
    /**
     *description: Array index exception
     */
    @ExceptionHandler(value=IndexOutOfBoundsException.class)
    public ResultMap<Object> IndexOutOfBoundsExceptionHandler(IndexOutOfBoundsException e){
    log.info("IndexOutOfBoundsExceptionHandler");
        System.out.println(Arrays.toString(e.getStackTrace()).split(",")[0]);
        return resultMap.error();
    }

    /**
     *description:json serialization exception
     */
    @ExceptionHandler(value= HttpMessageNotWritableException.class)
    public ResultMap<Object> HttpMessageNotWritableExceptionHandler(HttpMessageNotReadableException e){
        log.info("HttpMessageNotWritableException");
        System.out.println(Arrays.toString(e.getStackTrace()).split(",")[0]);
        return resultMap.error();
    }
    /**
     *description:sql insert error unique
     */
    @ExceptionHandler(value= DuplicateKeyException.class)
    public ResultMap<Object> DuplicateKeyExceptionHandler(DuplicateKeyException e){
        log.info("SQLIntegrityConstraintViolationException");
        System.out.println(Arrays.toString(e.getStackTrace()).split(",")[0]);
        return resultMap.error("文章已经存在!");
    }
    /**
     *description:other exception
     */
    @ExceptionHandler(value=Exception.class)
    public ResultMap ExceptionHandler(Exception e){
        log.info("Exception");
        log.info(e.toString());
        System.out.println(Arrays.toString(e.getStackTrace()).split(",")[0]);
        return resultMap.error();
    }
}
